/**
* Copyright (C)，2018，深圳万物安全科技有限公司
* FileName: index
* Author:   admin
* Data:     2018/11/10 12:12
* Description:
*/

<template>
    <div>
        <el-table :data="tasks" :style="styleObj">

            <el-table-column type="index" width="80" :label="$t('common.index')"></el-table-column>

            <el-table-column :label="$t('maps.tasksPage.name')" prop="taskName">
            </el-table-column>

            <el-table-column :label="$t('maps.tasksPage.progress')" prop="progress" width="200">
                <template slot-scope="scope">
                    <el-progress :percentage="scope.row.progress"></el-progress>
                </template>
            </el-table-column>

            <el-table-column :label="$t('maps.tasksPage.size')" prop="size">
                <template slot-scope="scope">
                    {{ scope.row.dataSize + ' (' + scope.row.dataSizeUnit + ')' }}
                </template>
            </el-table-column>

            <!--<el-table-column :label="$t('maps.tasksPage.useTime')" prop="useTime">-->
            <!--</el-table-column>-->

            <!--<el-table-column :label="$t('maps.tasksPage.needUseTime')" prop="needUseTime">-->
            <!--</el-table-column>-->

            <el-table-column :label="$t('common.operation')">
                <template slot-scope="scope">
                    <el-button type="text"
                               @click="startTask(scope)"
                               v-if="scope.row.taskStatus == 'stop'">
                        {{$t('maps.tasksPage.start')}}
                    </el-button>
                    <el-button type="text"
                               @click="stopTask(scope)"
                               v-if="scope.row.taskStatus == 'start'">
                        {{$t('maps.tasksPage.stop')}}
                    </el-button>
                    <el-button type="text"
                               @click="delTask(scope)">
                        {{$t('maps.tasksPage.delete')}}
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

    </div>
</template>

<script>

  let downloadTaskConf_BasicsDir = './static/downloadTaskConf/';
  let taskConf_Path = downloadTaskConf_BasicsDir + 'downloadtasks.data';

  import fs from 'fs';
  import request from 'request';
  import path from 'path'
  import Bagpipe from 'bagpipe'

  export default {
    name: "index",

    data() {
      return {
        msg: '地图离线下载工具',

        styleObj: {
          width: '100%',
          height: 0,
        },

        tasks: [],

        loading: null
      }
    },

    created: function () {
    },

    methods: {
      init() {

        let that = this;
        // 1.读取原有的任务配置文件，由JSON，转数组
        fs.readFile(taskConf_Path, 'utf8', function (err, data) {
          if (err) {
            alert(err);
          }

          that.tasks = JSON.parse(data);
        });

        this.loading.close();
      },

      resetSize() {
        let fullHeight = document.getElementById("loadPageDiv").offsetHeight;
        let dialogHeaderTitleHeight = document.getElementById("dialogHeaderTitle").offsetHeight;
        this.styleObj.height = fullHeight - dialogHeaderTitleHeight + 'px';
      },

      startTask(scope) {
        var task = scope.row;
        let taskDescFilePath = downloadTaskConf_BasicsDir + task.dataFileName;
        let downloadDir = task.downloadDir == '' ? 'D:/MapDown/' : task.downloadDir;

        scope.row.taskStatus = 'start';

        let that = this;
        setTimeout(()=>{
          that.downloadTaskBegin(that, task, taskDescFilePath, downloadDir);
        }, 2000);
      },
      stopTask(scope) {
        alert('停止暂不开发');
      },
      delTask(scope) {
        alert('删除暂不开发');
      },

      downloadTaskBegin(that, task, taskDescFilePath, downloadDir){
        // 1.读取原有的任务配置文件，由JSON，转数组
        fs.readFile(taskDescFilePath, 'utf8', function (err, data) {
          if (err) {
            alert(err);
          }
          var taskDescs = JSON.parse(data);
          var taskDesc = taskDescs[0];
          that.doDownload(that, taskDesc, task, taskDescFilePath, downloadDir);
        });
      },

      doDownload(that, taskDesc, task, taskDescFilePath, downloadDir) {
        var downloadImage = function(src, dstpath, callback) {
              request.head(src, function(err, res, body) {
                  if (src) {
                      request(src).pipe(fs.createWriteStream(dstpath)).on('close', function() {
                          callback(null, dstpath);
                      });
                  }
              });
          };
        var bagpipe = new Bagpipe(10);

        let zoomdatadesc = taskDesc.zoomdatadesc;
        let hearder = taskDesc.hearder;
        let urlMiddel = taskDesc.urlMiddel;
        let styleStr = taskDesc.styleJson;
        let urlEnd = styleStr.length == 0 ? '&customid=undefined' : '&styles=' +encodeURIComponent(styleStr);

        var currentDownload = taskDesc.currentDownload;
        let totalCount = taskDesc.totalCount;

        var currCount = 0;
        for( var index=0; index < zoomdatadesc.length; index++) {
          var temp = zoomdatadesc[index];
          let zoomLevel = temp.zoomLevel;

          if(typeof currentDownload.zoomLevel != 'undefined') {
            // 不是undefined的时候，说明已经下载过一部分，现在继续下载

            if(currentDownload.zoomLevel > zoomLevel){
              continue;
            }
          } else {
            currentDownload.zoomLevel = zoomLevel;
            currentDownload.left = -1;
            currentDownload.top = -1;
            currentDownload.totalCountCurr = 0;
          }

          let left = temp.left < currentDownload.left ? currentDownload.left : temp.left;
          let right = temp.right;
          let top = temp.top < currentDownload.top ? currentDownload.top : temp.top;
          let bottom = temp.bottom;

          var n=0;
          for (var x = left; x < right; x++) {
            for (var y = top; y < bottom; y++) {
              currentDownload.left = x;
              currentDownload.top = y;
              currentDownload.totalCountCurr ++;

              let url = hearder + '&x=' + x + '&y=' + y +'&z=' + zoomLevel + urlMiddel + urlEnd;

              let name = y + '.jpg';
              let dir = zoomLevel + '/' + x;
              let dstpath = downloadDir + dir + '/' + name;

              if (!fs.existsSync(dstpath)) {
                if (that.mkdirSync(downloadDir + dir)) {
                    // currCount++;
                    // // 界面进度条修改，这里还没有处理好
                    // task.progress = currCount / totalCount * 100;
                    // ++n;
                    // request(url).pipe(fs.createWriteStream(dstpath))

                    bagpipe.push(
                        downloadImage, url, dstpath, function (err, data) {
                            console.log('当前下载数量：' + n);
                            currCount++;
                            // 界面进度条修改，这里还没有处理好
                            task.progress = currCount / totalCount * 100;
                        }
                    );
                }
              }

            }
          }

          //循环结束后，上左的坐标重置为-1
          currentDownload.left = -1;
          currentDownload.top = -1;
          //级别加1
          currentDownload.zoomLevel++;
        }
      },

      mkdirSync(dirname) {
        if (fs.existsSync(dirname)) {
          return true;
        } else {
          if (this.mkdirSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
          }
        }
        return false
      },

      openFullScreen(str) {
        this.loading = this.$loading({
          lock: true,
          text: this.$t(str),
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      },

    },

    mounted: function () {
      this.resetSize();
      this.openFullScreen('maps.tasksPage.loadTasks')
      this.init();
    }

  }
</script>

<style scoped>

</style>